bookwiz.io / app / api / books / [id] / github-integration / commits / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server'
import { createServerSupabaseClient } from '@/lib/supabase'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const supabase = createServerSupabaseClient()
    const bookId = params.id

    // Get current user session
    const authHeader = request.headers.get('authorization')
    let user
    try {
      if (authHeader) {
        const { data: { user: authUser }, error: authError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''))
        if (!authError) user = authUser
      } else {
        const { data: { user: sessionUser }, error: sessionError } = await supabase.auth.getUser()
        if (!sessionError) user = sessionUser
      }
    } catch (e) {}
    if (!user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
    }

    // Get GitHub integration
    const { data: profile } = await supabase
      .from('profiles')
      .select('github_integrations')
      .eq('id', user.id)
      .single()
    const integration = profile?.github_integrations?.[bookId]
    if (!integration) {
      return NextResponse.json({ error: 'GitHub integration not found' }, { status: 404 })
    }
    const owner = integration.github_username
    const repo = integration.repository_name
    const accessToken = integration.access_token

    // Fetch commit history from GitHub
    const commitsUrl = `https://api.github.com/repos/${owner}/${repo}/commits?per_page=50`
    const commitsRes = await fetch(commitsUrl, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Accept': 'application/vnd.github.v3+json'
      }
    })
    if (!commitsRes.ok) {
      return NextResponse.json({ error: 'Failed to fetch commits from GitHub', status: commitsRes.status }, { status: 500 })
    }
    const commits = await commitsRes.json()
    // Map to simplified commit objects
    const commitList = (Array.isArray(commits) ? commits : []).map((c: any) => ({
      sha: c.sha,
      message: c.commit?.message,
      author: c.commit?.author?.name || c.author?.login,
      date: c.commit?.author?.date,
      html_url: c.html_url
    }))
    return NextResponse.json({ commits: commitList })
  } catch (error) {
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}